package com.fqcar.fqdf.ui;

import android.Manifest;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.widget.ImageView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.Response;
import com.fqcar.fqdf.R;
import com.fqcar.fqdf.core.BaseRequestActivity;
import com.fqcar.fqdf.entity.ResponseEntity;
import com.fqcar.fqdf.service.RequestOptService;
import com.fqcar.fqdf.util.ReqConstants;
import com.fqcar.fqdf.util.SharedPreferenceUtil;
import com.fqdf.framework.android.util.AndroidUtils;
import com.fqdf.framework.android.util.CheckLogicUtil;
import com.fqdf.framework.android.util.EnvUtil;
import com.fqdf.framework.android.util.LogUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;


public class WelcomeActivity extends BaseRequestActivity {

    @BindView(R.id.splash_iv)
    ImageView splashIv;


    private MaterialDialog requirePrimissionDialog;

    private MaterialDialog gotoSettingDialog;

    private final static String[] PERMISSION_VALUE = {
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};

    private Set<String> hasPerimissionSet = new HashSet<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        ButterKnife.bind(this);
        LogUtil.d(getClass(), "start oncreate");
        LogUtil.d(getClass(), "start initMyData");
//        SharedPreferenceUtil.setStringSPAttrs(this, SharedPreferenceUtil.AttrInfo.USER_TOKEN, "a5993163-78cb-5ce3-9a67-35361dbcb765");

        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                initMyData();
            }
        }, 3 * 1 * 1000);
    }

    public void initMyData() {

        // 先判断是否有权限。

        for (String item : PERMISSION_VALUE) {
            if (AndPermission.hasPermission(this, item) && !hasPerimissionSet.contains(item)) {
                hasPerimissionSet.add(item);
            }
        }

        LogUtil.d(getClass(), "hasperimission", hasPerimissionSet);

        if (AndPermission.hasPermission(this, PERMISSION_VALUE)) {


            // 有权限，直接do anything.
            if (EnvUtil.CheckDeviceIDS(this)) {
                Toast.makeText(this, "不支持模拟器", Toast.LENGTH_LONG).show();
                finish();
                System.gc();
                System.exit(0);
            } else {
                dismissRequirePrimissionDialog();
                dismissGotoSettingDialog();
//                PushManager.getInstance().initialize(this.getApplicationContext(), GTPushService.class);
//                PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), GTIntentService.class);
//                getGTToken(this);

//                if (hasToken()) {
//                    virtualLogin();
//                }

                if(CheckLogicUtil.isEmpty( SharedPreferenceUtil.getStringSPAttrs(WelcomeActivity.this, SharedPreferenceUtil.AttrInfo.USER_TOKEN, ""))){
                    Intent intent = new Intent(WelcomeActivity.this,LoginActivity.class);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent(WelcomeActivity.this,NormalHomeActivity.class);
                    startActivity(intent);
                }
                finish();
            }
        } else {
            // 申请权限。
            AndPermission.with(this)
                    .requestCode(ReqConstants.REQUEST_CODE_FOR_READ_PHONE_STATE)
                    .permission(PERMISSION_VALUE)
                    .send();
        }
        LogUtil.d(getClass(), "hasperimission", hasPerimissionSet);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initMyData();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 只需要调用这一句，其它的交给AndPermission吧，最后一个参数是PermissionListener。
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。

            for (String item : grantedPermissions) {
                hasPerimissionSet.add(item);
            }

            if (hasPerimissionSet.size() == PERMISSION_VALUE.length) {
                initMyData();
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
//            finish();

            for (String item : PERMISSION_VALUE) {
                if (!deniedPermissions.contains(item) && !hasPerimissionSet.contains(item)) {
                    hasPerimissionSet.add(item);
                }
            }

            boolean showRequirePrimissionDialog = false;

            for (String item : deniedPermissions) {
                if (!CheckLogicUtil.isEmpty(item) && ActivityCompat.shouldShowRequestPermissionRationale(WelcomeActivity.this, item)) {
                    showRequirePrimissionDialog = true;
                    break;
                }
            }

            if (showRequirePrimissionDialog) {
                dismissGotoSettingDialog();
                showRequirePeimissiomDialog();
            } else {
                dismissRequirePrimissionDialog();
                showGotoSettingDialog();
            }

        }
    };


    /**
     * 显示弹出去设置中设置权限的dialog
     */
    private void showGotoSettingDialog() {
        AndPermission.defaultSettingDialog(this, 400).show();
    }

    /**
     * 隐藏去设置中的权限的dialog
     */
    private void dismissGotoSettingDialog() {
        dismissDialog(gotoSettingDialog);
    }


    /**
     * 显示弹出去再次获取权限dialog
     */
    private void showRequirePeimissiomDialog() {

        if (requirePrimissionDialog == null) {
            requirePrimissionDialog = new MaterialDialog.Builder(this)
                    .title("请允许获取设备信息")
                    .content("我们需要获取设备信息，为您进行设备识别，否则您将无法正常使用" + getResources().getString(R.string.app_name))
                    .positiveColor(AndroidUtils.getColor(this, R.color.f)).positiveText("确定")
                    .negativeColor(AndroidUtils.getColor(this, R.color.f)).negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            // 申请权限。
                            AndPermission.with(WelcomeActivity.this)
                                    .requestCode(ReqConstants.REQUEST_CODE_FOR_READ_PHONE_STATE)
                                    .permission(PERMISSION_VALUE)
                                    .send();
                        }
                    })
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.cancel();
                            finish();
                        }
                    })
                    .show();
        }

        if (!requirePrimissionDialog.isShowing()) {
            requirePrimissionDialog.show();
        }
    }

    /**
     * 隐藏再次获取权限的dialog
     */
    private void dismissRequirePrimissionDialog() {
        dismissDialog(requirePrimissionDialog);
    }

    /**
     * 隐藏dialog
     *
     * @param dialog
     */
    private void dismissDialog(MaterialDialog dialog) {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }


    /**
     * 虚拟登陆
     */
    private void virtualLogin() {
        RequestOptService.tokenValidate(WelcomeActivity.this, tokenValidateListener, getDefaultErrorListener());
    }


    private Response.Listener<ResponseEntity> tokenValidateListener = new Response.Listener<ResponseEntity>() {
        @Override
        public void onResponse(ResponseEntity response) {

            if (handleResponse(response)) {
                SharedPreferenceUtil.clearSP(WelcomeActivity.this, SharedPreferenceUtil.SP_NAME_USER);
            } else {
//                UserInfo userInfo = JSON.parseObject(JSON.toJSONString(response.modelData.get("userInfo")), UserInfo.class);
//                SharedPreferenceUtil.setStringSPAttrs(WelcomeActivity.this, SharedPreferenceUtil.AttrInfo.USER_NICKNAME, userInfo.nickName);
//                SharedPreferenceUtil.setStringSPAttrs(WelcomeActivity.this, SharedPreferenceUtil.AttrInfo.USER_HEAD_IMG, userInfo.headImg);
//                SharedPreferenceUtil.setStringSPAttrs(WelcomeActivity.this, SharedPreferenceUtil.AttrInfo.USER_PHONE, userInfo.sim);
//                SharedPreferenceUtil.setStringSPAttrs(WelcomeActivity.this, SharedPreferenceUtil.AttrInfo.USER_CREDIT_STATE, CreditCheckState.getCheckStateName(Integer.valueOf(userInfo.verifyCredit)));
            }
        }
    };


    private boolean isFirstLogin() {
        return !SharedPreferenceUtil.getBooleanSPAttrs(this, SharedPreferenceUtil.AttrInfo.PROP_FIRST_USE, false);
    }

    private boolean hasToken() {
        return !CheckLogicUtil.isEmpty(SharedPreferenceUtil.getStringSPAttrs(this, SharedPreferenceUtil.AttrInfo.USER_TOKEN, ""));
    }

    /**
     * OPSTR_READ_PHONE_STATE 判断是否是系统AOP禁止的权限
     * <p>
     * # AppOpsManager.OPSTR_FINE_LOCATION 定位权限
     * # AppOpsManager.OPSTR_COARSE_LOCATION  定位权限
     * # AppOpsManager.OPSTR_READ_EXTERNAL_STORAGE  读SD卡权限
     * # AppOpsManager.OPSTR_WRITE_EXTERNAL_STORAGE  写SD卡权限
     * # AppOpsManager.OPSTR_READ_PHONE_STATE  读取手机状态权限
     *
     * @param aopPermission
     */
    private boolean isAopPermission(Context context, String aopPermission) {
        try {
            if (AndroidUtils.isSupportVersion(Build.VERSION_CODES.KITKAT)) {
                AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
                int checkResult = appOpsManager.checkOpNoThrow(
                        aopPermission, Binder.getCallingUid(), getPackageName());
                if (checkResult == AppOpsManager.MODE_ALLOWED) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

    private boolean isAopPermission(@NonNull Context context, @NonNull String... aopPermissions) {
        if (aopPermissions.length == 0) {
            return false;
        }

        for (String item : aopPermissions) {
            if (!isAopPermission(context, item)) {
                return false;
            }
        }

        return true;
    }
}
